package filelisting

import (
	"net/http"
	"os"
	"io/ioutil"
	"strings"
)

/**
 * @description 
 * @time 2018/5/6 23:42
 * @version 
 */

const prefix  = "/list/"

type useError string

func (e useError) Message() string {
	return e.Message()
}

func (e useError) Error() string {
	return string(e)
}

func HandleFileList(writer http.ResponseWriter, request *http.Request) error {

	if strings.Index(request.URL.Path, prefix) != 0 {
		return useError("path must start " + "with "+ prefix)
	}
 
	path := request.URL.Path[len(prefix):]		// /list/fib.txt
	file, pathError := os.Open(path)

	if pathError != nil {
		return pathError
	}

	defer file.Close()

	all, fileError := ioutil.ReadAll(file)
	if fileError != nil {
		return fileError
	}
	writer.Write(all)
	return nil
}